package com.gopay.commons.validator;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.gopay.commons.validator.check.DefaultValidator;
import com.gopay.commons.validator.form.ErrorMessage;
import com.gopay.commons.validator.form.Field;
import com.gopay.commons.validator.form.Validator;

/**
 * 校验工具类
 * 
 * @ValidatorTools.java
 * @author LEO
 * @2012-12-26 上午09:54:58 www.gopay.com.cn Inc.All rights reserved.
 */
public class ValidatorTools {
    private final static String PACKAGE_NAME = "com.gopay.commons.validator.check.";
    /**
     * 系统默认的校验是否为空类
     */
    private final static String DEFAULT_REQURIED_VALIDATOR = PACKAGE_NAME + "DefaultRequiredValidator";
    /**
     * 系统默认的长度校验类
     */
    private final static String DEFAULT_LENGTH_VALIDATOR = PACKAGE_NAME + "DefaultLengthValidator";
    /**
     * 系统默认的字符串长度校验类
     */
    private final static String DEFAULT_VALUELENGTH_VALIDATOR = PACKAGE_NAME + "DefaultValueLengthValidator";
    /**
     * 系统默认的正则表达式校验类
     */
    private final static String DEFAULT_PATTERN_VALIDATOR = PACKAGE_NAME + "DefaultPatternValidator";

    private final static String SUFFIX_1 = "\\u0024\\u007B";
    private final static String SUFFIX_2 = "}";
    private final static String FIELD_VALUE = "fieldValue";
    private final static String DISPLAY_NAME = "displayName";

    /**
     * 
     * @param field
     */
    public static ErrorMessage validator(Field field) {
        if (field == null) {
            return null;
        }

        List<Validator> validators = field.getValidators();
        if (validators == null || validators.size() == 0) {
            return null;
        }

        String validatorClass = "";
        Validator validator = null;
        ErrorMessage errorMessage = null;
        for (Iterator<Validator> it = validators.iterator(); it.hasNext();) {
            validator = (Validator) it.next();
            validatorClass = getValidatorClass(validator);
            DefaultValidator defaultValidator = getInstance(validatorClass);
            boolean flag = defaultValidator.execute(field);
            if (!flag) {
                // 错误信息
                errorMessage = new ErrorMessage();
                errorMessage.setFieldName(field.getFieldName());
                errorMessage.setMessage(buildMessage(validator.getMessage(), field));
                return errorMessage;
            }
        }

        return null;
    }

    /**
     * 获取验证类的实例
     * 
     * @param validatorClass
     * @return
     */
    private static DefaultValidator getInstance(String validatorClass) {
        DefaultValidator defaultValidator = null;

        try {
            Class<?> clas = Class.forName(validatorClass);
            defaultValidator = (DefaultValidator) clas.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return defaultValidator;
    }

    /**
     * 获取验证类的名称
     * 
     * @param validator
     * @return
     */
    private static String getValidatorClass(Validator validator) {
        if (validator == null) {
            return null;
        }

        if (StringUtils.isBlank(validator.getType())) {
            if (validator.isRequried()) {
                validator.setType(DEFAULT_REQURIED_VALIDATOR);
            } else if (StringUtils.isNotBlank(validator.getPattern())) {
                validator.setType(DEFAULT_PATTERN_VALIDATOR);
            } else if (StringUtils.isNotBlank(validator.getMinLength())
                    || StringUtils.isNotBlank(validator.getMaxLength())) {
                validator.setType(DEFAULT_LENGTH_VALIDATOR);
            } else if (StringUtils.isNotBlank(validator.getMinValue())
                    || StringUtils.isNotBlank(validator.getMaxValue())) {
                validator.setType(DEFAULT_VALUELENGTH_VALIDATOR);
            }
        }

        return validator.getType();
    }

    /**
     * 渲染错误信息 将其中包含${fieldValue}标记替换成fieldValue
     * 
     * @param message
     * @param fieldValue
     * @return
     */
    private static String buildMessage(String message, Field field) {
        if (StringUtils.isNotBlank(message)) {
            if (field.getValue() != null) {
                message = message.replaceAll(SUFFIX_1 + FIELD_VALUE + SUFFIX_2, field.getValue().toString());
            }
            if (StringUtils.isNotBlank(field.getDisplayName())) {
                message = message.replaceAll(SUFFIX_1 + DISPLAY_NAME + SUFFIX_2, field.getDisplayName());
            }
        }

        return message;
    }
}
